package com.sc.VenusQueryBeta.ui.fragments.setting.child;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.rxbus.RxBus;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.setting.SettingContract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.model.sqlite.DataBaseDao;
import com.sc.VenusQueryBeta.presenter.setting.SettingPresenter;
import com.sc.VenusQueryBeta.ui.activites.details.AboutUsActivity;
import com.sc.VenusQueryBeta.ui.activites.login.ChangePasswordActivity;
import com.sc.VenusQueryBeta.ui.activites.setting.AboutKingStarActivity;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.CompositeDisposable;

/**
 * Created by SC-02 on 2018/9/19.
 * 子HomeFragment
 * 1继承BaseMVPCompatFragment
 * 2必须实现契约类里面的view接口并且重写对应的方法（该fragment有请求就必须实现，重写，不然会报错）
 */

public class SettingFragment extends BaseMVPCompatFragment<SettingContract.SettingPresenter> implements SettingContract.ISettingView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.setting_title)
    AppBarLayout settingTitle;
    @BindView(R.id.pwd_setting)
    LinearLayout pwdSetting;
    @BindView(R.id.about_us)
    LinearLayout aboutUs;
    @BindView(R.id.about_kingstar)
    LinearLayout aboutKingstar;
    @BindView(R.id.setting_name)
    TextView settingName;
    @BindView(R.id.btn_quit)
    Button btnQuit;
    private CompositeDisposable compositeDisposable;
    private UsersLoginBean loginBean;
    private TextView ok;
    private TextView cancel;
    private PopupWindow popupWindow;
    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;
    private DataBaseDao dataBaseDao;
    private SQLiteDatabase rdb;

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return SettingPresenter.newInstance();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_setting_child;
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        LogUtils.e("SettingFragment===========initUI");
        settingName.setText(SpUtils.getString(MyApplication.app, Constants.USER, ""));
        loginBean = SpUtils.getObject(MyApplication.app, UsersLoginBean.class);
        if (loginBean != null && !loginBean.getId().equals("")) {
            //已经登录
            btnQuit.setVisibility(View.VISIBLE);
            pwdSetting.setVisibility(View.VISIBLE);
            settingName.setText(SpUtils.getString(MyApplication.app, Constants.USER, ""));
        } else {
            btnQuit.setVisibility(View.GONE);
            pwdSetting.setVisibility(View.GONE);
        }

    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        LogUtils.e("SettingFragment===========onSupportVisible");
        loginBean = SpUtils.getObject(MyApplication.app, UsersLoginBean.class);
        if (loginBean != null && !loginBean.getId().equals("")) {
            //已经登录
            btnQuit.setVisibility(View.VISIBLE);
            pwdSetting.setVisibility(View.VISIBLE);
            settingName.setText(SpUtils.getString(MyApplication.app, Constants.USER, ""));
        } else {
            btnQuit.setVisibility(View.GONE);
            pwdSetting.setVisibility(View.GONE);
            settingName.setText("设置");
        }
//        StatusBarUtils.setColor(mActivity, getColor(R.color.theme_color));
    }

    @Override
    public void initData() {
        super.initData();
        loginBean = SpUtils.getObject(MyApplication.getContext(), UsersLoginBean.class);
        compositeDisposable = new CompositeDisposable();
        LogUtils.e("initData");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.rxBusUnbund(compositeDisposable);
    }

    /**
     * 提供实例化对象
     *
     * @return
     */
    public static SettingFragment newInstance() {
        return new SettingFragment();
    }

    @OnClick({R.id.pwd_setting, R.id.about_us, R.id.about_kingstar})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pwd_setting://修改密码
                startNewActivity(ChangePasswordActivity.class);
                break;
            case R.id.about_us: //跳转至关于我们
                startNewActivity(AboutUsActivity.class);
                break;
            case R.id.about_kingstar:  //跳转至关于金星
                startNewActivity(AboutKingStarActivity.class);
                break;

        }
    }

    @Override
    public void showNetworkError() {

    }

    /**
     * 回调退出登录
     *
     * @param exitLoginBean
     */
    @Override
    public void exitLoginBean(String exitLoginBean) {
        SpUtils.clear(MyApplication.app);
        SpUtils.putBoolean(MyApplication.app, Constants.OUT_DATE, true);
        SpUtils.putString(MyApplication.app, Constants.PHONE, loginBean.getId());
        SpUtils.putString(MyApplication.app, Constants.AREADECODE, loginBean.getAreaCode());
        SpUtils.putBoolean(MyApplication.app, Constants.LOGINOUT, true);
        ToastUtils.showToast(getString(R.string.loginouted));
        btnQuit.setVisibility(View.GONE);
        pwdSetting.setVisibility(View.GONE);
        settingName.setText(R.string.setting);
        hideProgressDialog();
        Intent intentx = new Intent("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
        //发送本地广播
        LocalBroadcastManager.getInstance(mContext).sendBroadcastSync(intentx);

        dataBaseDao = new DataBaseDao(MyApplication.app, loginBean.getId(), 11);
        rdb = dataBaseDao.databasehelper.getWritableDatabase();
        rdb.close();
    }


    @OnClick(R.id.btn_quit)
    public void onViewClicked() {
        inputOtherPwdWindow();
    }

    /**
     * 退出登录弹出框
     */
    private void inputOtherPwdWindow() {
        final View contentView = LayoutInflater.from(mActivity).inflate(R.layout.pop_exit, null);
        ok = contentView.findViewById(R.id.OK);
        cancel = contentView.findViewById(R.id.quxiao);
        if (popupWindow == null) {
            popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        }
        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 0.5f;
        mActivity.getWindow().setAttributes(lp);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                lp.alpha = 1f;
                mActivity.getWindow().setAttributes(lp);
            }
        });

        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true); //设置点击menu以外其他地方以及返回键退出
        popupWindow.setOutsideTouchable(true);   //设置触摸外面时消失
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        // 设置弹出窗体的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable(MyApplication.app.getResources(), (Bitmap) null));
        ColorDrawable cd = new ColorDrawable();
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popupWindow.dismiss();
                }
            });
        }
        // 5 在底部显示
        popupWindow.showAtLocation(btnQuit, Gravity.CENTER, 0, 0);
        //点击确定
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgressDialog(getString(R.string.now_login_out));
                mPresenter.exit(loginBean.getId());
                popupWindow.dismiss();
            }
        });
        //点击取消
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getView()!=null) {
            getView().setBackground(getResources().getDrawable(com.hengjun.kingstar.sdk.R.color.white));
        }
        loginBean = SpUtils.getObject(MyApplication.app, UsersLoginBean.class);
        if (loginBean != null && !loginBean.getId().equals("")) {
            //已经登录
            btnQuit.setVisibility(View.VISIBLE);
            pwdSetting.setVisibility(View.VISIBLE);
            settingName.setText(SpUtils.getString(MyApplication.app, Constants.USER, ""));
            LogUtils.e("已经登录");
        } else {
            btnQuit.setVisibility(View.GONE);
            pwdSetting.setVisibility(View.GONE);
            LogUtils.e("设置");
            settingName.setText(R.string.setting);
        }
    }
    @Override
    public boolean onBackPressedSupport() {
        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
//            mActivity.setIsTransAnim(false);
            mActivity.finish();
        } else {
            TOUCH_TIME = System.currentTimeMillis();
//                ToastUtils.showToast(R.string.press_again);
            ToastUtils.showToast(R.string.exit_again);
        }
        return true;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        LogUtils.e("onLazyInitView");
    }
}


